import React, { memo, ReactNode, FC, useState, useRef, ElementRef } from "react";
import { BannerWrapper, LeftWrapper, RightWrapper, BannerControl } from "./style";
import { Carousel } from "antd";

import { useAppSelector, appShallowEqual } from "@/stores";
import classNames from "classnames";
import { url } from "inspector";
interface IProps {
  children?: ReactNode;
}

const TobBanner: FC<IProps> = memo((props) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const bannerRef = useRef<ElementRef<typeof Carousel>>(null);
  const { banners } = useAppSelector(
    (state) => ({
      banners: state.recommend.banners,
    }),
    appShallowEqual
  );

  function handleAfterChange(index: number) {
    setCurrentIndex(index);
  }

  function goTo(index: number) {
    bannerRef.current?.goTo(index);
  }

  /* 获取背景图片 */
  let bgImageUrl;
  if (currentIndex >= 0 && banners.length > 0) {
    bgImageUrl = banners[currentIndex].imageUrl + "?imageView&blur=40x20";
  }

  return (
    <BannerWrapper style={{ background: `url(${bgImageUrl}) center center /6000px` }}>
      <div className="banner wrap-v2">
        <LeftWrapper>
          <Carousel ref={bannerRef} effect="fade" autoplay autoplaySpeed={3000} dots={false} afterChange={handleAfterChange}>
            {banners.map((item) => {
              return <img src={item.imageUrl} alt={item.title} key={item.imageUrl}></img>;
            })}
          </Carousel>
          <ul className="dots">
            {banners.map((item, index) => {
              return (
                <li key={item.imageUrl}>
                  <span onClick={() => goTo(index)} className={classNames("item", { active: index === currentIndex })}></span>
                </li>
              );
            })}
          </ul>
        </LeftWrapper>

        <RightWrapper></RightWrapper>
        <BannerControl>
          <button className="btn left" onClick={() => bannerRef.current?.prev()}></button>
          <button className="btn right" onClick={() => bannerRef.current?.next()}></button>
        </BannerControl>
      </div>
    </BannerWrapper>
  );
});

export default TobBanner;
